
#1.导包
import rclpy #ros2基本函数的命名空间入口
from rclpy.node import Node #ros2的py节点
from base_interfaces_demo.msg import Student

#3.定义节点
class MinimalPublisher(Node):
    #初始化函数
    def __init__(self):
        super().__init__('student_publisher_py') #继承父类Node节点,初始化节点名称
        # 3-1.创建发布方；
        self.publisher_ = self.create_publisher(Student,"topic_stu",10)
        # 3-2.创建定时器；
        timer_period = 0.5
        self.timer_ = self.create_timer(timer_period,self.timer_callback)
        self.i = 0

    # 3-3.组织消息并发布
    def timer_callback(self):
        stu = Student()
        stu.name = '大嘟嘟'
        stu.age = self.i
        stu.height = 1.65
        self.publisher_.publish(stu)
        self.get_logger().info('发布的学生消息(py):name=%s,age=%d,height=%.2f' % (stu.name, stu.age, stu.height))
        self.i+=1

#初始化
def main(args = None):
    # 2,初始化ROS2客户端
    rclpy.init(args = args)
    # 4,调用spin函数,并传入节点对象；
    minimalPublisher = MinimalPublisher()
    rclpy.spin(minimalPublisher)
    # 5,释放资源
    rclpy.shutdown()

if __name__ == "__main__":
    main()